//
//  NewFeatureViewController.swift
//  WeiBo09
//
//  Created by 裘明 on 15/9/6.
//  Copyright © 2015年 qm. All rights reserved.
//


import UIKit

/// 新特性图片的数量
private let MQNewFeatureCount = 4
/// 重用标识符
private let MQNewFeatureCellID = "MQNewFeatureCellID"

class NewFeatureViewController: UICollectionViewController {
    
    // 调用父类的函数去初始化布局属性
    init() {
        super.init(collectionViewLayout: UICollectionViewFlowLayout())
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 1.注册可重用cell
        self.collectionView!.registerClass(NewFeatureCell.self, forCellWithReuseIdentifier: MQNewFeatureCellID)
        
        // 2.设置布局属性
        setupLayout()
    }
    
    /// 设置布局
    private func setupLayout () {
        
        let layout = collectionView?.collectionViewLayout as! UICollectionViewFlowLayout
        
        layout.itemSize = view.bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.showsVerticalScrollIndicator = false
        collectionView?.pagingEnabled = true
    }

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return MQNewFeatureCount
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        // 1.在缓存池中寻找可重用cell
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(MQNewFeatureCellID, forIndexPath: indexPath) as! NewFeatureCell
        
        // 2.给cell赋值
        cell.imageIndex = indexPath.item
        
        // 3.返回cell
        return cell
    }
    
    //
    override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        
        // 获取当前显示Cell的索引
        let index = collectionView.indexPathsForVisibleItems().last!
        
        // 判断当前是否是最后一个cell
        if index.item == MQNewFeatureCount - 1 {
            // 获取当前cell
            let cell = collectionView.cellForItemAtIndexPath(index) as! NewFeatureCell
            
            cell.showStartButten()
        }
    }
    
}

private class NewFeatureCell: UICollectionViewCell {
    
    /// 设置图片的索引，并同时给头像赋值
    private var imageIndex: NSInteger = 0 {
        didSet {
            iconView.image = UIImage(named: "new_feature_\(imageIndex + 1)")
            startButten.hidden = true
        }
    }
    
    ///  通知AppDelegate却换控制器
    @objc private func cilckStartButten() {
        NSNotificationCenter.defaultCenter().postNotificationName(MQSwitchRootViewController, object: nil)
    }
    
    
    
    // 动画显示开始体验
    private func showStartButten() {
        // 1.显示按钮
        startButten.hidden = false
        // 2.设置弹性系数
        startButten.transform = CGAffineTransformMakeScale(0, 0)
        
        /// 3.设置动画
        ///
        /// - returns: usingSpringWithDamping：弹性系数，越小越弹 initialSpringVelocity：起始速度
        UIView.animateWithDuration(1.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 16, options: [], animations: {
                // 恢复到初始形变状态
                self.startButten.transform = CGAffineTransformIdentity
            
            }) { (_) -> Void in}
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        // 设置界面
        setupUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        // 设置界面
        setupUI()
    }
    /// 设置界面
    private func setupUI() {
        // 1.添加控件
        addSubview(iconView)
        addSubview(startButten)
        
        // 2.设置约束
        iconView.frame = bounds
        
        startButten.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: startButten, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: startButten, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: -160))
        
        
    }
    /// 1.图像视图
    private lazy var iconView = UIImageView()
    
    /// 2.开始按钮
    private lazy var startButten: UIButton = {
       
        let btn = UIButton()
        btn.setTitle("开始体验", forState: UIControlState.Normal)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
        btn.sizeToFit()
        btn.addTarget(self, action: "cilckStartButten", forControlEvents: UIControlEvents.TouchUpInside)
        return btn
    }()
}




